package bsf.baseservice;

import bsf.base.BsfException;
import bsf.baseservice.configmanager.IConfigManagerProvider;
import bsf.log.DebugLog;

import java.net.URL;
import java.net.URLClassLoader;

/**
 * Created by chejiangyi on 2017/4/5.
 * 基础服务上下文
 */
public final class BaseServiceContext {
    /**
     * 注册配置中心接口
     */
    public static IConfigManagerProvider ConfigManagerProvider = null;

    /**
     注册监控平台接口

     */
    //public static IMonitorProvider MonitorProvider = null;

    static {
        //自己实现IOC 依赖注入

        ConfigManagerProvider = tryToRegisterContext("bsf.baseservice.configmanager.ConfigManagerProvider", new String[] { "bsf-full", "bsf-baseservice-configmanager" },IConfigManagerProvider.class);

        //MonitorProvider = TryToRegisterContext<IMonitorProvider>("BSF.BaseService.Monitor.MonitorProvider", new String[] { "BSF.Full", "BSF.BaseService.Monitor" });
    }


    private static <T> T tryToRegisterContext(String classname, String[] jarpaths,Class<T> cls) {
            URLClassLoader classLoader = null; Exception error = null;
            for (String jarpath : jarpaths) {
                try {
                    URL url = new URL(jarpath);
                    classLoader = new URLClassLoader(new URL[]{url});
                    Class<? extends T> myClass = (Class<? extends T>) classLoader.loadClass(classname);
                    T obj = (T) myClass.newInstance();
                    return obj;
                } catch (Exception exp) {
                    error = exp;
                }
            }
        DebugLog.write("【警告】注册基础服务上下文注册失败:"+classname,BaseServiceContext.class);
            return null;
            //throw new BsfException("注册基础服务上下文失败",error,BaseServiceContext.class);

    }


}